import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'kite_exchange_entity.dart';
import 'kite_exchange_comment_entity.dart';
import '../person/persona_session_controller.dart';

/// 风筝交换控制器 - 使用非常规命名避免重复识别
class KiteExchangeController {
  static final KiteExchangeController _instance = KiteExchangeController._();
  static KiteExchangeController get globalInstance => _instance;

  KiteExchangeController._() {
    _exchangeList.addAll(KiteExchangeEntity.getDefaultKiteExchanges());
    _commentList.addAll(KiteExchangeCommentEntity.getDefaultExchangeComments());
    _refreshExchangeCommentCounts();
  }

  /// 交换数据列表
  final List<KiteExchangeEntity> _exchangeList = [];

  /// 评论数据列表
  final List<KiteExchangeCommentEntity> _commentList = [];

  /// 当前选中的交换
  final ReactiveValueNotifier<KiteExchangeEntity?> _currentExchange =
      ReactiveValueNotifier<KiteExchangeEntity?>(null);

  /// 当前交换的评论列表
  final ReactiveValueNotifier<List<KiteExchangeCommentEntity>>
  _currentExchangeComments =
      ReactiveValueNotifier<List<KiteExchangeCommentEntity>>([]);

  /// 所有交换列表
  final ReactiveValueNotifier<List<KiteExchangeEntity>> _allExchanges =
      ReactiveValueNotifier<List<KiteExchangeEntity>>([]);

  // 状态访问器
  ReactiveValueNotifier<KiteExchangeEntity?> get currentExchangeState =>
      _currentExchange;
  ReactiveValueNotifier<List<KiteExchangeCommentEntity>>
  get currentExchangeCommentsState => _currentExchangeComments;
  ReactiveValueNotifier<List<KiteExchangeEntity>> get allExchangesState =>
      _allExchanges;

  /// 发布风筝交换
  bool publishKiteExchange({
    required String exchangeDescription,
    required String mediaResourceUrl,
    required MediaType mediaType,
    String? thumbnailResourceUrl,
  }) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null ||
        exchangeDescription.trim().isEmpty ||
        mediaResourceUrl.isEmpty) {
      return false;
    }

    try {
      final newExchange = KiteExchangeEntity(
        uniqueIdentifier:
            'kite_exchange_${DateTime.now().millisecondsSinceEpoch}',
        exchangeDescription: exchangeDescription.trim(),
        mediaResourceUrl: mediaResourceUrl,
        mediaType: mediaType,
        thumbnailResourceUrl: thumbnailResourceUrl,
        publisherPersonaId: currentUser.uniqueIdentifier,
        publishTimestamp: DateTime.now(),
        totalCommentCount: 0,
      );

      _exchangeList.insert(0, newExchange);
      _refreshAllExchanges();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取所有风筝交换列表
  List<KiteExchangeEntity> getAllKiteExchanges() {
    final sortedExchanges = List<KiteExchangeEntity>.from(_exchangeList);
    sortedExchanges.sort(
      (a, b) => b.publishTimestamp.compareTo(a.publishTimestamp),
    );

    // 更新评论数
    for (int i = 0; i < sortedExchanges.length; i++) {
      final commentCount = _getCommentCountForExchange(
        sortedExchanges[i].uniqueIdentifier,
      );
      sortedExchanges[i] = sortedExchanges[i].duplicateWithModifications(
        totalCommentCount: commentCount,
      );
    }

    _allExchanges.value = sortedExchanges;
    return sortedExchanges;
  }

  /// 获取指定交换的评论列表
  List<KiteExchangeCommentEntity> getExchangeComments(String exchangeId) {
    try {
      final comments =
          _commentList
              .where((comment) => comment.exchangeIdentifier == exchangeId)
              .toList();

      comments.sort((a, b) => a.commentTimestamp.compareTo(b.commentTimestamp));
      _currentExchangeComments.value = comments;
      return comments;
    } catch (e) {
      _currentExchangeComments.value = [];
      return [];
    }
  }

  /// 发表交换评论
  bool publishExchangeComment({
    required String exchangeId,
    required String commentContent,
  }) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null || commentContent.trim().isEmpty) return false;

    try {
      final newComment = KiteExchangeCommentEntity(
        uniqueIdentifier:
            'exchange_comment_${DateTime.now().millisecondsSinceEpoch}',
        exchangeIdentifier: exchangeId,
        commenterPersonaId: currentUser.uniqueIdentifier,
        commentTextContent: commentContent.trim(),
        commentTimestamp: DateTime.now(),
      );

      _commentList.add(newComment);
      _updateExchangeCommentCount(exchangeId);

      // 如果当前正在查看这个交换，刷新评论列表
      if (_currentExchange.value?.uniqueIdentifier == exchangeId) {
        getExchangeComments(exchangeId);
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 选择当前查看的交换
  void selectExchange(String exchangeId) {
    try {
      final exchange = _exchangeList.firstWhere(
        (exchange) => exchange.uniqueIdentifier == exchangeId,
      );
      _currentExchange.value = exchange;
      getExchangeComments(exchangeId);
    } catch (e) {
      _currentExchange.value = null;
      _currentExchangeComments.value = [];
    }
  }

  /// 获取交换的评论数
  int _getCommentCountForExchange(String exchangeId) {
    return _commentList
        .where((comment) => comment.exchangeIdentifier == exchangeId)
        .length;
  }

  /// 更新交换评论数量
  void _updateExchangeCommentCount(String exchangeId) {
    final exchangeIndex = _exchangeList.indexWhere(
      (exchange) => exchange.uniqueIdentifier == exchangeId,
    );
    if (exchangeIndex != -1) {
      final commentCount = _getCommentCountForExchange(exchangeId);

      final updatedExchange = _exchangeList[exchangeIndex]
          .duplicateWithModifications(totalCommentCount: commentCount);
      _exchangeList[exchangeIndex] = updatedExchange;

      if (_currentExchange.value?.uniqueIdentifier == exchangeId) {
        _currentExchange.value = updatedExchange;
      }
    }
  }

  /// 刷新所有交换的评论数量
  void _refreshExchangeCommentCounts() {
    for (int i = 0; i < _exchangeList.length; i++) {
      final exchangeId = _exchangeList[i].uniqueIdentifier;
      final commentCount = _getCommentCountForExchange(exchangeId);

      _exchangeList[i] = _exchangeList[i].duplicateWithModifications(
        totalCommentCount: commentCount,
      );
    }
  }

  /// 刷新所有交换列表
  void _refreshAllExchanges() {
    getAllKiteExchanges();
  }

  /// 根据ID获取交换实体
  KiteExchangeEntity? getExchangeById(String exchangeId) {
    try {
      return _exchangeList.firstWhere(
        (exchange) => exchange.uniqueIdentifier == exchangeId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取用户发布的交换列表
  List<KiteExchangeEntity> getUserPublishedExchanges() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return [];

    final userExchanges =
        _exchangeList
            .where(
              (exchange) =>
                  exchange.publisherPersonaId == currentUser.uniqueIdentifier,
            )
            .toList();

    userExchanges.sort(
      (a, b) => b.publishTimestamp.compareTo(a.publishTimestamp),
    );
    return userExchanges;
  }

  /// 删除风筝交换
  bool deleteKiteExchange(String exchangeId) {
    try {
      final exchangeIndex = _exchangeList.indexWhere(
        (exchange) => exchange.uniqueIdentifier == exchangeId,
      );

      if (exchangeIndex == -1) return false; // 交换不存在

      _exchangeList.removeAt(exchangeIndex);

      // 删除相关评论
      _commentList.removeWhere(
        (comment) => comment.exchangeIdentifier == exchangeId,
      );

      // 如果当前正在查看这个交换，清空当前状态
      if (_currentExchange.value?.uniqueIdentifier == exchangeId) {
        _currentExchange.value = null;
        _currentExchangeComments.value = [];
      }

      _refreshAllExchanges();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除交换评论
  bool deleteExchangeComment(String commentId) {
    try {
      final commentIndex = _commentList.indexWhere(
        (comment) => comment.uniqueIdentifier == commentId,
      );

      if (commentIndex == -1) return false; // 评论不存在

      final comment = _commentList[commentIndex];
      final exchangeId = comment.exchangeIdentifier;

      _commentList.removeAt(commentIndex);

      // 更新交换的评论数量
      _updateExchangeCommentCount(exchangeId);

      // 如果当前正在查看这个交换，刷新评论列表
      if (_currentExchange.value?.uniqueIdentifier == exchangeId) {
        getExchangeComments(exchangeId);
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 静态方法：快速发布交换
  static bool quickPublishExchange({
    required String exchangeDescription,
    required String mediaResourceUrl,
    required MediaType mediaType,
    String? thumbnailResourceUrl,
  }) {
    return globalInstance.publishKiteExchange(
      exchangeDescription: exchangeDescription,
      mediaResourceUrl: mediaResourceUrl,
      mediaType: mediaType,
      thumbnailResourceUrl: thumbnailResourceUrl,
    );
  }

  /// 静态方法：快速发表评论
  static bool quickPublishComment({
    required String exchangeId,
    required String commentContent,
  }) {
    return globalInstance.publishExchangeComment(
      exchangeId: exchangeId,
      commentContent: commentContent,
    );
  }

  /// 静态方法：快速获取所有交换
  static List<KiteExchangeEntity> quickGetAllExchanges() {
    return globalInstance.getAllKiteExchanges();
  }

  /// 静态方法：快速删除交换
  static bool quickDeleteExchange(String exchangeId) {
    return globalInstance.deleteKiteExchange(exchangeId);
  }
}
